﻿using K9Nano.MultiTenancy;
using Microsoft.AspNetCore.Http;

namespace K9Nano.AspNetCore.MultiTenancy
{
    /// <summary>
    /// Cache tenant during a request
    /// </summary>
    public class HttpContextTenantResolverCache : ITenantResolverCache
    {
        private const string CacheItemKey = "TenantCacheItem";

        public TenantResolverCacheItem Value
        {
            get => _httpContextAccessor.HttpContext?.Items[CacheItemKey] as TenantResolverCacheItem;

            set
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext == null)
                {
                    return;
                }

                httpContext.Items[CacheItemKey] = value;
            }
        }

        private readonly IHttpContextAccessor _httpContextAccessor;

        public HttpContextTenantResolverCache(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    }
}